package cronservice

import (
	"fmt"
	"github.com/gogf/gf/net/ghttp"
	"go-middle/app/common/model/cron"
	"net/http"
	"time"
)

//Handler 任务执行接口
type Handler interface {
	Run(task cron.Task) (string, error)
}

//HTTPHandler HTTP任务
type HTTPHandler struct{}

//Run 执行HTTP任务
func (h *HTTPHandler) Run(task cron.Task) (result string, err error) {
	c := ghttp.NewClient()
	if task.Timeout <= 0 {
		c.SetTimeout(time.Second * 30) //默认超时30秒
	} else {
		c.SetTimeout(time.Duration(task.Timeout) * time.Second)
	}
	resp, err := c.DoRequest(task.Method, task.Command)
	if err != nil {
		return
	}
	result = resp.ReadAllString()
	// 返回状态码非200，均为失败
	if resp.StatusCode != http.StatusOK {
		err = fmt.Errorf("HTTP状态码非200-->%d", resp.StatusCode)
	}
	return
}

func createHandler(taskModel cron.Task) Handler {
	var handler Handler = nil
	switch taskModel.Protocol {
	case "HTTP":
		handler = new(HTTPHandler)
	case "SHELL":
		break
	}
	return handler
}
